import { View, Textarea, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { forwardRef, ReactNode, useEffect, useRef, useState } from "react";
import deleteIcon from '@/assets/images/delete.png'
import dragIcon from '@/assets/images/drag.png'
import removeIcon from '@/assets/images/remove-topic.png'
import deleteTopic from '@/assets/images/delete-topic.png'


import { STORE_KEY, TOPIC_NUM } from "@/common/config";
import './draggableContainer.scss'
import { USER_PROFILE_STATUS } from "@/typing";
export interface DraggableProps {
    items: [];
    sort?: string;
    dragRowItemCom?: ReactNode;
    handleDelete: (index: number) => void;
}

enum DragDirection {
    UP = "UP",
    DOWN = "DOWN",
}

/**
 *  拖拽容器组件
 */
const DraggableContainer=forwardRef<HTMLDivElement, DraggableProps>((props,ref)=>{
    const { items, sort = "id" ,handleDelete} = props;
    // const [dragTopicList, setDragTopList] = useState<Array<any>>([]);
    const [dragList, setDragList] = useState<Array<any>>(items);
    // 拖拽item的高度
    const dragItemHeight = useRef(0);
    // 起始y轴坐标
    const [startY, setStartY] = useState<number>(0);
    // 起始索引
    const [startIndex, setStartIndex] = useState<number>(0);
    // 结束索引
    const [endIndex, setEndIndex] = useState<number>(0);
    // 拖动项
    const [draging, setDraging] = useState<{ status: boolean; direction: DragDirection; y: number; difference: number; transform: string }>({
        status: false, //状态 - 按下时设置为true,结束设置为false
        direction: DragDirection.UP, // 拖拽的方向
        y: 0, //拖动时y轴的坐标
        difference: 0, // 拖拽时y轴坐标 -  按下时的坐标
        transform: "", // 存储拖拽的transform的值
    });

    /**
     * 按下
     */
    const onTouchStart = (e: any, item, index: number) => {
        const { pageY } = e.changedTouches[0];
        setDraging({
            ...draging,
            status: true,
        });
        setStartY(pageY);
        setStartIndex(index);
    };

    /**
     * 拖拽
     */
    const onTouchMove = (e: any, item, index: number) => {
        const { pageY } = e.changedTouches[0];
        setDraging({
            status: true,
            direction: pageY > startY ? DragDirection.DOWN : DragDirection.UP,
            y: pageY,
            difference: pageY > startY ? pageY - startY : startY - pageY,
            transform: `translateY(${pageY > startY ? pageY - startY : "-" + (startY - pageY)}px)`,
        });
    };

    /**
     *  松开
     */
    const onTouchEnd = (e: any, item, index: number) => {
       // 计算新索引
    computeNewIndex(draging.direction, draging.difference);
    // 交换列表项
    moveArrayItem();
    // 重置状态
    _reset();
   
    };

    /**
     * 更新列表
     */
    const moveArrayItem = () => {
        const validEndIndex = Math.max(0, Math.min(dragList.length - 1, endIndex));
    const newArray = [...dragList];
    const [removedItem] = newArray.splice(startIndex, 1);
    newArray.splice(validEndIndex, 0, removedItem);
    setDragList(newArray);
    // console.log(newArray)
     Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(newArray))
    };

    /**
     * 重置
     */
    const _reset = () => {
        setDraging({
            status: false,
            direction: DragDirection.UP,
            y: 0,
            difference: 0,
            transform: "translateY(0px)",
        });
        setStartY(0);
        setStartIndex(0);
        setEndIndex(0);
    };

    /**
     * 获取当个item的高度
     */
    useEffect(() => {
        setDragList(props.items)
       
        Taro.nextTick(() => {
            const idStr = `#drag-${dragList[0][sort]}`;
            // console.log(idStr)
            Taro.createSelectorQuery()
                .select(idStr)
                .boundingClientRect()
                .exec((res) => {
                    console.log(res)
                    if(res&& res[0].height !=null){
                        dragItemHeight.current = res[0].height;
                    }
                    
                });

              
        });
    }, [props.items]);

    /**
     *  计算最新位置的索引
     */
    const computeNewIndex = (direction: DragDirection, difference: number) => {
        let newIndex;
        if (direction == DragDirection.UP) {
            newIndex = startIndex - Math.floor(difference / dragItemHeight.current);
        } else {
            newIndex = startIndex + Math.floor(difference / dragItemHeight.current);
        }
        setEndIndex(newIndex);
     

        // console.log(dragTopicList)
    };

    /**
     * 位置偏移
     */
    const getTranslateY = (index: number) => {
        if (!draging.status || draging.difference < 10) {
            return "translateY(0px)";
        }
        if (index === startIndex) {
            return draging.transform;
        }
        if (draging.direction === DragDirection.UP) {
            if (index >= endIndex && index < startIndex) {
                return `translateY(${dragItemHeight.current}px)`;
            }
            return "translateY(0px)";
        } else if (draging.direction === DragDirection.DOWN) {
            if (index <= endIndex && index > startIndex) {
                return `translateY(-${dragItemHeight.current}px)`;
            }
            return "translateY(0px)";
        }
    };
    const handleInput = (e, currentKey) => {
         const storeUserStatus = Taro.getStorageSync(STORE_KEY.USER_PROFILE_STATUS) || USER_PROFILE_STATUS.unknown;
        console.log(e)
        
        const newValue = e.detail.value; // 获取新的输入值
      console.log(dragList)
        const updatedList = dragList.map(item => {
            console.log(item)
            const sortKey = Number(item.id) >=0 ? item.id: item[sort] ;
            console.log(sortKey)
            console.log('currentKey----'+currentKey)
            if (sortKey === currentKey) {
                return { ...item, title: newValue }; // 更新对应项的 topicName
            }
            return item; // 其他项保持不变
        });
        console.log(storeUserStatus)
        console.log(USER_PROFILE_STATUS.enable)
        Taro.setStorageSync(STORE_KEY.TOPIC, JSON.stringify(updatedList))
        
        setDragList(updatedList); // 更新状态
    };
    /**
     * 监听拖拽行属性的变化
     */
    useEffect(() => {
      
        if (!draging.status || draging.difference < 10) {
            return;
        }
        computeNewIndex(draging.direction, draging.difference);
    }, [draging]);

    return (
        
        <View
           ref={ref}
            style={{
                overflowY: draging.status ? "hidden" : "auto",
            }}
        >
            {dragList.length >0 &&dragList.map((item, index) => {
                
                return (
                    <View className="flex items-center justify-between mb-30px bg-#fff pr-30px box-border"
                    catchMove
                        key={item[sort]?item[sort]:item.id}
                        id={`drag-${item[sort]}`}
                        style={{

                            zIndex: index === startIndex ? 10 : 1,
                            transform: getTranslateY(index),
                        }}
                    >
                      
                        {dragList.length > 1 &&<View className="h-full w-56px flex items-center justify-center"  onTouchStart={(e) => {
                                    e.stopPropagation();
                                    onTouchStart(e, item, index);
                                }}
                                onTouchMove={(e) => {
                                    e.stopPropagation();
                                    onTouchMove(e, item, index);
                                }}
                                onTouchEnd={(e) => {
                                    e.stopPropagation();
                                    onTouchEnd(e, item, index);
                                }}>
                            <Image src={removeIcon} className="w-16px h-26px"
                               
                            ></Image></View>}
                            
                          <View className="w-580px bg-#fff ml-26px " id={`${item.id}`}>
                            <Textarea onInput={(e)=>handleInput(e,Number(item.id) >=0 ? item.id: item[sort])}  id={`drag-${item[sort]}`} value={item.title} className="w-full py-36px  pl-6px pr-54px box-border  text-32px tetx-#333333 max-h-270px  leading-40px" style='height:108rpx'  placeholder='话题描述' maxlength={TOPIC_NUM} autoHeight></Textarea>

                        </View>
                        {dragList.length > 1&& <Image src={deleteTopic} className="w-22px h-22px  " onClick={()=>handleDelete(index)}></Image>}
                      
                       
                    </View>


                );
            })}
           
           
        </View>
    );
})

export default DraggableContainer;


